package io.vov.vitamio.fragment;

import io.vov.vitamio.TVApplication;
import io.vov.vitamio.activity.VideoActivity;
import io.vov.vitamio.entity.OnlineVideo;
import io.vov.vitamio.entity.OnlineVideoSource;
import io.vov.vitamio.entity.TVProgram;
import io.vov.vitamio.tvpaser.OnlineTVParser;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.j256.ormlite.stmt.QueryBuilder;
import com.naduolai.android.util.StringUtil;
import com.ndjh.onlinetv.R;
import com.ndjh.ormlite.NDJHBaseDao;
import com.umeng.analytics.MobclickAgent;

public class TVFragment extends Fragment {
	private static final String TAG = "TVFragment";
	private DataAdapter mAdapter;
	private static List<OnlineVideo> root = new ArrayList<OnlineVideo>();
	private VideoActivity mTVPlayerActivity;
	private String mCurrentTab = "";
	private NDJHBaseDao<OnlineVideo, Integer> mCurrentTabOnlineDao;
	private NDJHBaseDao<OnlineVideoSource, Integer> mCurrentTabOnlineVideoSourceDao;
	private NDJHBaseDao<TVProgram, Integer> mTVProgramsDao;
	private boolean onClickable = true;
	private View view;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mTVPlayerActivity = (VideoActivity) activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e(TAG, "onCreate");
		try {
			mCurrentTabOnlineDao = TVApplication.getInstance().getHelper().getDao(OnlineVideo.class);
			;
			mCurrentTabOnlineVideoSourceDao = TVApplication.getInstance().getHelper().getDao(OnlineVideoSource.class);
			mTVProgramsDao = TVApplication.getInstance().getHelper().getDao(TVProgram.class);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Log.e(TAG, "onCreateView");
		view = inflater.inflate(R.layout.tv_programs_list, container, false);
		return view;

	}

	// 完成Fragment的初始化，不对前面不是已经初始化好了么？
	// 这个方法主要是初始化那些你需要你的父Activity或者Fragment的UI已经被完整初始化才能初始化的元素。
	// 具体你看图中的位置你能看出点端倪来。比如UI的元素没被解析反射进来，你还想用？ 想得美，等它初始化完，你再用。
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.e(TAG, "onActivityCreated");
		if (StringUtil.isEmpty(mCurrentTab)) {
			mTVPlayerActivity.restartApplication(); 
		} else {
			try {
				if (mCurrentTab.equals("频道")) {
					Log.e("频道", "频道");
					root = mCurrentTabOnlineDao.queryForAll();
				}
				if (mCurrentTab.equals("收藏")) {
					Log.e("收藏", "收藏");
					root = mCurrentTabOnlineDao.queryAllWhereEqData("isFavorite", true, "id", true);
				}
				if (mCurrentTab.equals("设置")) {
					root = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			init(view);
		}
	}

	private void init(View view) {
		ListView onlinetv_listview = (ListView) view.findViewById(R.id.online_tv_listview);
		if (mAdapter == null) {
			mAdapter = new DataAdapter(getActivity(), root);
			onlinetv_listview.setAdapter(mAdapter);
		} else {
			mAdapter.notifyDataSetChanged();
		}
		onlinetv_listview.setItemsCanFocus(true);
		onlinetv_listview.setSelection(mDefaultPosition - 1);
		mAdapter.setSelectedPosition(mDefaultPosition);
		onlinetv_listview.setOnScrollListener(new ScrollListener());

	}

	protected class ScrollListener implements OnScrollListener {

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            // do nothing 
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (SCROLL_STATE_TOUCH_SCROLL == scrollState) {
                View currentFocus = mTVPlayerActivity.getCurrentFocus();
                if (currentFocus != null) {
                    currentFocus.clearFocus();
                }
            }
        }

    }
	
	@Override
	public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Log.e(TAG, TAG + "-----onInflate");
		super.onInflate(activity, attrs, savedInstanceState);
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		// 这个Bundle会被传入到onCreate、onCreateView
		super.onSaveInstanceState(savedInstanceState);
		Log.e(TAG, "onSaveInstanceState");
	}

	@Override
	public void onDestroyView() {
		// 清除所有跟视图相关的资源
		super.onDestroyView();
		Log.e(TAG, "onDestroyView");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
	}

	@Override
	public void onDetach() {
		Log.e(TAG, "onDetach");
		super.onDetach();

	}

	private int mDefaultPosition;

	protected static final int DELAY = 0x01;
	protected static final int FAVORITE = 0x02;
	protected static final int GOTONEXT = 0x03;
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DELAY:
				new TVProgramsListTask().execute(msg.obj.toString());
				break;
			case FAVORITE:
				Log.e("MobclickAgent友盟", msg.obj.toString());
				MobclickAgent.onEvent(mTVPlayerActivity, "CHANNEL_FAVORITE_COUNT", msg.obj.toString());
				break;

			case GOTONEXT:
				try {
//					QueryBuilder<OnlineVideoSource,Integer> defaultPreparedQuery = mCurrentTabOnlineVideoSourceDao.queryBuilder();
//					defaultPreparedQuery.where().eq("sourcenum", msg.obj.toString()).and().eq("defaultLink", true);
//					OnlineVideoSource  OnlineVideoSource= mCurrentTabOnlineVideoSourceDao.queryForFirst(defaultPreparedQuery.prepare());
//					if(OnlineVideoSource != null && !StringUtil.isEmpty(OnlineVideoSource.getLink())){
//						mTVPlayerActivity.goToNext(OnlineVideoSource.getLink());
//					}else{
//						QueryBuilder<OnlineVideoSource,Integer> preparedQuery = mCurrentTabOnlineVideoSourceDao.queryBuilder();
//						preparedQuery.where().eq("sourcenum", msg.obj.toString());
//						OnlineVideoSource = mCurrentTabOnlineVideoSourceDao.queryForFirst(preparedQuery.prepare());
//						if(OnlineVideoSource != null && !StringUtil.isEmpty(OnlineVideoSource.getLink())){
//							mTVPlayerActivity.goToNext(OnlineVideoSource.getLink());
//						}
//					}
					
//						mTVPlayerActivity.goToNext(mCurrentTabOnlineVideoSourceDao.queryData("SELECT * FROM ONLINEVIDEOSOURCE WHERE SOURCENUM = '" + msg.obj.toString() + "' limit 0,1").getLink());
					mTVPlayerActivity.goToNext(msg.obj.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}

				break;
			default:
				break;
			}
		}
	};

	/** 数据适配 */
	private class DataAdapter extends BaseAdapter {
		private Context ctx;
		private List<OnlineVideo> mdata;
		private int selectedPosition = -1;// 选中的位置

		public DataAdapter(Context context, List<OnlineVideo> data) {
			ctx = context;
			mdata = data;
		}

		@Override
		public int getCount() {
			return mdata != null ? mdata.size() : 0;
		}

		@Override
		public OnlineVideo getItem(int position) {
			return mdata != null ? mdata.get(position) : null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		@SuppressLint("ResourceAsColor")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			final OnlineVideo item = mdata.get(position);
			if (convertView == null) {
				final LayoutInflater mInflater = getActivity().getLayoutInflater();
				convertView = mInflater.inflate(R.layout.tv_programs_item, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			} else {
				convertView.clearFocus();
				holder = (ViewHolder) convertView.getTag();
			}
			final View tempView = convertView;
			holder.mTvProgramsTitle.setText(item.id + "   " + item.title);
			holder.mTvProgramsTitle.setFocusableInTouchMode(true);
			holder.mTvProgramsFavorite.setText("收藏");
			// holder.mTvProgramsFavorite.setFocusableInTouchMode(true);
			if (mCurrentTab.equals("收藏")) {
				holder.mTvProgramsFavorite.setText("取消");
			}
			if (selectedPosition == item.id) {
				Log.e("selectedPosition", "" + selectedPosition);
				holder.mTvProgramsTitle.requestFocus();
				// try {
				// if(mCurrentTabOnlineDao.queryWhereEqData(new
				// String[]{"num","isFavorite"}, new Object[]{item.num,true},
				// null, null) != null && !mCurrentTab.equals("收藏")){
				// tempView.setBackgroundResource(R.drawable.programs_already_favorite);
				// holder.mTvProgramsFavorite.setText("");
				// holder.mTvProgramsFavorite.setFocusable(false);
				// }else{
				// holder.mTvProgramsFavorite.setFocusable(true);
				// tempView.setBackgroundResource(R.drawable.programs_tv_title_bg);
				// }
				// Message message = handler.obtainMessage(DELAY);
				// message.obj = item.source_code;
				// handler.removeMessages(DELAY);
				// handler.sendMessageDelayed(message, 2000);
				// } catch (SQLException e) {
				// e.printStackTrace();
				// }
			}
			holder.mTvProgramsTitle.setOnFocusChangeListener(new View.OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) {
						try {
							if (mCurrentTabOnlineDao.queryWhereEqData(new String[] { "num", "isFavorite" }, new Object[] { item.num, true }, null, null) != null && !mCurrentTab.equals("收藏")) {
								tempView.setBackgroundResource(R.drawable.programs_already_favorite);
								holder.mTvProgramsFavorite.setText("");
								holder.mTvProgramsFavorite.setFocusable(false);
							} else {
								holder.mTvProgramsTitle.setTextColor(Color.parseColor("#1B1D24"));
								holder.mTvProgramsFavorite.setFocusable(true);
								tempView.setBackgroundResource(R.drawable.programs_tv_title_bg);
							}
							// new Thread(new Runnable() {
							//
							// @Override
							// public void run() {
							// OnlineTVParser.getInstance().getTVProgramList(item.source_code,
							// new Date());
							// }
							// }).start();
							Message message = handler.obtainMessage(DELAY);
							message.obj = item.source_code;
							handler.removeMessages(DELAY);
							handler.sendMessageDelayed(message, 2000);
						} catch (SQLException e) {
							e.printStackTrace();
						}
					} else {
						holder.mTvProgramsTitle.setTextColor(Color.parseColor("#F1F1F1"));
						tempView.setBackgroundColor(Color.parseColor("#00FFFFFF"));
					}

				}
			});

			holder.mTvProgramsTitle.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// v.clearFocus();
					try {
						Message message = handler.obtainMessage(DELAY);
						message.obj = item.source_code;
						handler.removeMessages(DELAY);
						handler.sendMessageDelayed(message, 1000);
						// v.requestFocusFromTouch();

						Message msg = handler.obtainMessage(GOTONEXT);
						msg.obj = item.getNum();
						handler.removeMessages(GOTONEXT);
						handler.sendMessageDelayed(msg, 1000);
						setSelectedPosition(item.id);

					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			});
			holder.mTvProgramsFavorite.setOnFocusChangeListener(new View.OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) {
						holder.mTvProgramsFavorite.setTextColor(Color.parseColor("#1B1D24"));
						tempView.setBackgroundResource(R.drawable.programs_tv_favorite_bg);
					} else {
						holder.mTvProgramsFavorite.setTextColor(Color.parseColor("#021e2e"));
						tempView.setBackgroundColor(Color.parseColor("#00FFFFFF"));
					}

				}
			});
			holder.mTvProgramsFavorite.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					try {
						v.requestFocusFromTouch();
						if (!mCurrentTab.equals("收藏")) {
							Log.e("TVFragment", "收藏");
							item.setFavorite(true);
							mCurrentTabOnlineDao.update(item);
							mTVPlayerActivity.reshData(1);
							// MobclickAgent.onEvent(getActivity(),
							// "CHANNEL_FAVORITE_COUNT", item.title);

							Message message = handler.obtainMessage(FAVORITE);
							message.obj = item.title;
							handler.removeMessages(FAVORITE);
							handler.sendMessageDelayed(message, 2000);
						} else {
							Log.e("TVFragment", "取消收藏");
							item.setFavorite(false);
							mCurrentTabOnlineDao.update(item);
							mTVPlayerActivity.reshData(0);
						}
						v.requestFocus();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			});
			return convertView;
		}

	}

	class ViewHolder {
		private Button mTvProgramsTitle;
		private Button mTvProgramsFavorite;

		public ViewHolder(View view) {
			this.mTvProgramsTitle = (Button) view.findViewById(R.id.tv_programs_title);
			this.mTvProgramsFavorite = (Button) view.findViewById(R.id.tv_programs_favorite);
		}
	}

	private class TVProgramsListTask extends AsyncTask<String, Object, List> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected List doInBackground(String... params) {
			List<TVProgram> mTVProgramList = null;
			try {
				mTVProgramList = mTVProgramsDao.queryAllWhereEqData("tvCode", params[0], "playTime", true);
				if (mTVProgramList == null || mTVProgramList.size() <= 0) {
					Log.e(TAG, "节目预告：网络获取");
					mTVProgramList = OnlineTVParser.getInstance().getTVProgramList(params[0], new Date());
					if (mTVProgramList != null) {

						for (int i = 0; i < mTVProgramList.size(); i++) {
							// Log.e("节目", mTVProgramList.get(i).getTitle());
							mTVProgramsDao.create(mTVProgramList.get(i));
						}
					}
				} else {
					SimpleDateFormat simpleDateParser = new SimpleDateFormat("yyyy-MM-dd");
					String today = simpleDateParser.format(new Date())/* "2013-03-17 16:50:00" */;
					String playTime = mTVProgramList.get(0).getPlayTime();
					playTime = playTime.split(" ")[0];

					if (today.compareTo(playTime) > 0) {
						Log.e(TAG, "需要更新数据");
						// 需要更新数据
						mTVProgramsDao.deleteData("delete from 'TvProgram'");
						Log.e(TAG, "更新后节目预告：网络获取");
						mTVProgramList = OnlineTVParser.getInstance().getTVProgramList(params[0], new Date());
						if (mTVProgramList != null) {

							for (int i = 0; i < mTVProgramList.size(); i++) {

								mTVProgramsDao.create(mTVProgramList.get(i));
							}
						}
					}
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}
			return mTVProgramList;

		}

		@Override
		protected void onPostExecute(List result) {
			mTVPlayerActivity.showProgramsList(result);

		}

	}

	public void setData(String str, int Position) {
		mCurrentTab = str;
		mDefaultPosition = Position;
	}

	/**
	 * 防止3秒内连续点击操作
	 * 
	 * @return
	 */
	public boolean onClickable() {
		if (!onClickable) {
			return false;
		}
		onClickable = false;
		// 使用线程启用所有账号的授权按钮
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					// 暂停3秒
					Thread.sleep(3000);
				} catch (Exception e) {
					e.printStackTrace();
				}
				// 设置所有账号绑定按钮可用标识
				onClickable = true;
			}
		}).start();
		return true;
	}
}
